<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="brandPage.key"
        placeholder="请输入品牌名称"
        style="width: 300px"
        class="filter-item"
        :clearable="true"
        @keyup.enter.native="handleBrandFilter"
      />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleBrandFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px" type="primary" icon="el-icon-edit" @click="brandDialogVisible = true">
        新增
      </el-button>
      <el-button :loading="brandTableDownloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleBrandExport">
        导出
      </el-button>
    </div>

    <!-- 表格组件 -->
    <el-table v-loading="brandTableLoading" :data="brandTableData" style="width: 100%">
      <el-table-column prop="categoryFullName" label="商品分类" />
      <el-table-column prop="brandName" label="品牌名称" width="180" />
      <el-table-column prop="brandLetter" label="首字母" />
      <el-table-column prop="brandImage" label="LOGO" />
      <el-table-column fixed="right" label="操作" width="150">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleClick(scope.row)">查看</el-button>
          <el-button size="mini">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      layout="total, sizes, prev, pager, next, jumper"
      :page-size="brandPage.pageSize"
      :page-count="brandPage.totalPages"
      ::page-sizes="brandPage.pageSegments"
      :total="brandPage.totalCount"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />

    <!-- 品牌新增/编辑对话框 -->
    <el-dialog title="品牌" :visible.sync="brandDialogVisible">
      <el-form ref="brandForm" :model="brandForm" :rules="brandRules">
        <el-form-item label="品牌名称" :label-width="formLabelWidth">
          <el-input v-model="brandForm.brandName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="品牌首字母" :label-width="formLabelWidth">
          <el-input v-model="brandForm.brandLetter" autocomplete="off" />
        </el-form-item>
        <el-form-item label="选择品牌分类" :label-width="formLabelWidth">
          <!-- 商品分类级联选择器 -->
          <el-cascader
            v-model="brandForm.categoryIds"
            :clearable="true"
            :filterable="true"
            :options="categoryOptions"
            :props="categoryProps"
            @active-item-change="handleCategoryItemChange"
          />
        </el-form-item>
        <el-form-item label="上传LOGO">
          <el-upload
            class="logo-uploader"
            action="https://jsonplaceholder.typicode.com/posts/"
            :show-file-list="false"
            :on-success="handleLogoUploadSuccess"
            :before-upload="beforeLogoUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="logo">
            <i v-else class="el-icon-plus logo-uploader-icon" />
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="brandDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSaveBrand()">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { listCategoriesByParentId } from '@/api/category'
import { listBrandByPage, saveBrand } from '@/api/brand'

export default {
  data() {
    const validateBrandName = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入品牌名称'))
      } else {
        callback()
      }
    }

    return {
      brandDialogVisible: false,

      brandTableLoading: false,
      brandTableData: [],

      brandPage: {
        key: '',
        currentPage: 1,
        pageSize: 10,
        pageSegments: [],
        totalPages: 0,
        totalCount: 0
      },

      brandForm: {
        brandName: '',
        brandLetter: '',
        brandImage: '',
        categoryIds: []
      },

      brandRules: {
        brandName: [{ required: true, trigger: 'blur', validator: validateBrandName }]
      },

      categoryOptions: [
        {
          id: '',
          subCategories: []
        }
      ],
      categoryProps: {
        label: 'categoryName',
        value: 'id',
        children: 'subCategories'
      },
      imageUrl: '',
      brandTableDownloadLoading: false,

      formLabelWidth: '120px'
    }
  },
  created() {
    // 查询品牌
    const params = {
      key: this.key,
      currentPage: this.brandPage.currentPage,
      orderField: 'id'
    }
    this.listBrands(params)

    // 查询商品分类
    this.listCategories(null)
  },
  methods: {
    /**
     * 分页查询品牌
     */
    listBrands(params) {
      this.brandTableLoading = true

      listBrandByPage(params)
        .then((res) => {
          if (!res) {
            return
          }

          this.brandPage.currentPage = parseInt(res.currentPage)
          this.brandPage.pageSegments = parseInt(res.pageSegments)
          this.brandPage.pageSize = parseInt(res.pageSize)
          this.brandPage.totalPages = parseInt(res.totalPages)
          this.brandPage.totalCount = parseInt(res.totalCount)

          if (res.rows) {
            this.brandTableData = res.rows
          } else {
            this.brandTableData = []
          }
        })
        .catch(err => {
          console.log(err)
        })
        .then(() => {
          this.brandTableLoading = false
        })
    },

    /**
     * 分级查询商品分类
     */
    async listCategories(parentId) {
      const newCategoryOptions = await listCategoriesByParentId(parentId)
      if (!newCategoryOptions) {
        return
      }

      newCategoryOptions.forEach(categoryOption => {
        if (categoryOption.leaf === 0) {
          categoryOption.subCategories = []
        }
      })

      if (!parentId) {
        this.categoryOptions = newCategoryOptions
        return
      } else {
        this.fillCategoryOptions(parentId, newCategoryOptions, this.categoryOptions)
      }
    },

    /**
     * 条件查询
     */
    handleBrandFilter() {
      // 查询品牌
      this.listBrands(this.brandPage)
    },

    /**
     * 导出
     */
    handleBrandExport() {
      this.brandTableDownloadLoading = true
      import('@/vendor/Export2Excel').then((excel) => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['', '', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.brandTableDownloadLoading = false
      })
    },

    /**
     * 单击一行数据
     */
    handleClick(row) {
      console.log(row)
    },

    /**
     * 翻页
     */
    handleCurrentChange(currentPage) {
      // 查询品牌
      this.brandPage.currentPage = currentPage
      this.listBrands(this.brandPage)
    },

    /**
     * 修改每页数据量
     */
    handleSizeChange(pageSize) {
      this.brandPage.pageSize = pageSize
      this.listBrands(this.brandPage)
    },

    /**
     * 选择商品分类项后查询其下级列表
     */
    async handleCategoryItemChange(val) {
      if (!val) {
        return
      }
      const parentId = val[val.length - 1]
      await this.listCategories(parentId)
    },

    /**
     * 上传Logo成功
     */
    handleLogoUploadSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },

    /**
     * 上传Logo之前
     */
    beforeLogoUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    /**
     * 保存商品分类
     */
    handleSaveBrand() {
      this.$refs.brandForm.validate(valid => {
        if (valid) {
          saveBrand(this.brandForm)
            .then(res => {
              this.brandDialogVisible = false
              this.resetBrandForm()
              // 重新查询
              this.listBrands(this.brandPage)
            })
            .catch(err => {
              console.log(err)
            })
        }
      })
    },

    /**
     * 重置品牌表单
     */
    resetBrandForm() {
      this.brandForm.brandName = ''
      this.brandForm.brandLetter = ''
      this.brandForm.brandImage = ''
      this.brandForm.categoryIds = []
    },

    /**
     * 根据parentId递归查询对应的CategoryOption
     */
    fillCategoryOptions(parentId, newCategoryOptions, categoryOptions) {
      if (!newCategoryOptions || !categoryOptions) {
        return
      }

      for (let i = 0; i < categoryOptions.length; i++) {
        if (categoryOptions[i].id === parentId) {
          categoryOptions[i].subCategories = newCategoryOptions
          return
        }
        this.fillCategoryOptions(parentId, newCategoryOptions, categoryOptions[i].subCategories)
      }
    }
  }
}
</script>
<style>
.logo-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.logo-uploader .el-upload:hover {
  border-color: #409eff;
}
.logo-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.logo {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
